# -*- coding: UTF-8 -*-


class DBStore(object):
    
    __db_map = {}

    def __init__(self, core):
        self.core = core


    def load(self, database, newConnect = False):
        if not self.__db_map.has_key(database) or newConnect:
           self.__db_map[database] = DBDriver(self.core, database)
        return self.__db_map[database]


    def __del__(self):
        for db in self.__db_map.items():
            db.close()
        self.__db_map.clear()


class DBDriver(object):

    __db, __cursor = None, None


    def __init__(self, core, database):
        self.core = core
        self.__db = self.__connect(database)
        self.__cursor = self.__db.cursor()


    def __connect(self, database):
        configDict = self.core.config.MYSQL_DATABASE
        if not configDict.has_key(database):
            raise Exception(u'未获取到数据库[%s]的配置信息' % database)

        config = configDict[database]
        mysqldb = self.core.loader.module('MySQLdb')
        return mysqldb.connect(config.get('host'), config.get('user'), config.get('pwd'), database, use_unicode = config.get('use_unicode', True), charset = config.get('charset', 'utf8'))


    def insert(self, tablename, insertData):
        if not insertData or not isinstance(insertData, dict):
            raise Exception(u'写入数据的格式不符合规范')

        fields, values = [], []
        for k, v in insertData.items():
            fields.append(self.filterField(k))
            values.append(self.filterValue(v))

        sql = 'INSERT INTO %s (%s) VALUES (%s)' % (self.filterField(tablename), ','.join(fields), ','.join(values))
        
        try:
            self.__cursor.execute(sql)
            insertId = self.__db.insert_id()
            self.__db.commit()
            return self.core.lib.outputobj(True, '数据写入成功', insertId) if insertId > 0 else self.core.lib.outputobj(False, '数据写入失败')
        except Exception as e:
            self.core.lib.stdout(sql, isExit = False)
            self.core.lib.stdout(str(e), isExit = False)
            return self.core.lib.outputobj(False, '数据写入发生异常：%s' % str(e))


    def update(self, tablename, whereString, updateData):
        if not updateData or not isinstance(updateData, dict):
            raise Exception(u'更新数据的格式不符合规范')

        updateString = ','.join(['%s=%s' % (self.filterField(k), self.filterValue(v)) for k, v in updateData.items()])

        sql = 'UPDATE %s SET %s' % (self.filterField(tablename), updateString)
        if whereString:
            sql += ' WHERE %s' % whereString

        self.__cursor.execute(sql)
        self.__db.commit()
        affectedRow = self.__cursor.rowcount
        return self.core.lib.outputobj(True, '数据更新成功', affectedRow) if affectedRow> 0 else self.core.lib.outputobj(False, '入数据失入败')


    def selectAll(self, tablename, queryString, whereString):
        if not queryString:
            queryString = '*'

        sql = 'SELECT %s FROM %s' % (queryString, self.filterField(tablename))
        if whereString:
            sql += ' WHERE %s' % whereString

        self.__cursor.execute(sql)
        hitData = self.__cursor.fetchall()
        return self.core.lib.outputobj(True, '成功获取数据', hitData) if hitData else self.core.lib.outputobj(False, '未查询到符合要求的数据')


    def filterField(self, field):
        return '`' + field +'`'


    def filterValue(self, value):
        if isinstance(value, unicode):
            return "'" + value.encode('utf-8') + "'"
        if isinstance(value, str):
            return "'" + value + "'"
        return str(value)


    def close(self):
        self.__db.close()
